﻿using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm;
using System.ServiceModel;
using System.Data.SqlClient;
using System.Reflection;
using System.Data.Common;

using System.Data.Metadata.Edm;
using System.Data.EntityClient;

namespace Crm2011.BusinessTransaction
{
    /// <summary>
    /// Custom context used to pass around valuable services between plugin and business process
    /// </summary>
    public class ExecutionContext
    {
        public IPluginExecutionContext Context { set; get; }
        public ITracingService TracingService { set; get; }
        public Entity TargetEntity { set; get; }
        public IOrganizationService Service { set; get; }
        public SqlConnection PluginConnection { set; get; }

        private const string crmEntitiesConnectionStringTemplate = "metadata=res://*/Crm.csdl|res://*/Crm.ssdl|res://*/Crm.msl;provider=System.Data.SqlClient;provider connection string=\"{0}\"";

        /// <summary>
        /// Creates new EF CRMEntities context using the same connection string as plugin connection
        /// </summary>
        /// <returns>new instance of EF CRMEntities context</returns>
        public CRMEntities GetNewCRMEntitiesContext()
        {
            if (PluginConnection != null)
            {
                var cs = string.Format(crmEntitiesConnectionStringTemplate, PluginConnection.ConnectionString);
                return new CRMEntities(cs);
            }
            
            throw new ArgumentNullException("PluginConnection");
        }

        public ExecutionContext()
        {
        }


    }


}

